package com.fw.application.controller;


import cn.hutool.bloomfilter.bitMap.BitMap;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.application.controller.base.BaseController;
import com.fw.common.Builder;
import com.fw.common.IdXD;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.TbMoneys;
import com.fw.system.web.model.entity.TbUser;
import com.fw.system.web.service.ITbMoneysService;
import com.fw.system.web.service.ITbUserService;
import com.fw.utils.AliSmsUtil;
import com.fw.utils.AuthUtils;
import com.fw.utils.RandomUtils;
import com.fw.utils.StringUtils;
import com.sun.org.apache.bcel.internal.generic.IXOR;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.BitSet;
import java.util.List;

import static com.fw.mes.ResultUtils.success;


@RestController
@RequestMapping("/user")
@Api(tags = "用户相关")
@CrossOrigin
public class TbUserController implements BaseController {


    @Autowired
    private ITbUserService userService;
    @Autowired
    private ITbMoneysService moneysService;
    @Autowired
    private IdXD idXD;
    @Autowired
    private AuthUtils authUtils;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/register")
    @ApiOperation("手机号注册 如果有邀请码sysHost 直接放进表单参数")
    public Result register(@RequestBody TbUser user) {

        TbUser tbUser = userService.getOne(Wrappers.<TbUser>lambdaQuery().eq(TbUser::getPhone, user.getPhone()));
        if (tbUser != null)
            return new Result().fail(0, "手机号被占用");
        if (StringUtils.isNotEmpty(user.getSysHost())) {
            TbUser parentUser = userService.getOne(Wrappers.<TbUser>lambdaQuery().eq(TbUser::getSysHost, user.getSysHost()));
            user.setParentId(parentUser.getId());
        }
        user.setCreateTime(LocalDateTime.now());
        user.setId(idXD.nextId());
        user.setIsType(0);
        user.setIsStatus(1);
        user.setSysHost(RandomUtils.createRandomString(8));
        user.setVipLevel(0);
        user.insert();
        //初始化余额表
        Builder.of(TbMoneys::new).with(TbMoneys::setId, idXD.nextId())
                .with(TbMoneys::setCreateTime, LocalDateTime.now())
                .with(TbMoneys::setUserId, user.getId())
                .with(TbMoneys::setIsStatus, 1).build().insert();
        return success();
    }

    @GetMapping("/login")
    @ApiOperation("login")
    public Result login(@RequestParam String phone, @RequestParam(required = false) String passWord) {
        TbUser tbUser = userService.getOne(Wrappers.<TbUser>lambdaQuery().eq(TbUser::getPhone, phone));
        if (tbUser == null)
            return new Result().fail(0, "该用户不存在");
        if (!StringUtils.isBlank(passWord)) {
            if (!tbUser.getPassWord().equals(passWord))
                return new Result().fail(0, "密码错误");
        }
        String json = JSON.toJSON(tbUser).toString();
        String token = authUtils.createJWT(tbUser.getId(), json, null);
        return success(token);
    }

    //发送验证码
    @GetMapping("/sendCode")
    @ApiOperation("发送验证码")
    public Result sendCode(@RequestParam String phone) {
        String code = RandomUtils.createRandomString(6);
        redisTemplate.opsForValue().set(phone, code);
        AliSmsUtil.send(phone, code);
        return success(code);
    }


    @GetMapping("/checkCode")
    @ApiOperation("验证验证码")
    public Result checkCode(@RequestParam String phone, @RequestParam String code) {
        String codes = (String) redisTemplate.opsForValue().get(phone);
        if (StringUtils.isEmpty(codes))
            return new Result().fail(0, "请取获取验证码");
        if (!code.equals(codes))
            return new Result().fail(0, "验证码错误");
        return success();
    }

    @PostMapping("/update")
    @ApiOperation("完善用户信息 除了身份证信息不让填写 单独填写的")
    public Result update(@RequestBody TbUser user) {

        String userId = this.getUser().getId();
        TbUser tbUser = userService.getById(userId);
        if (tbUser == null)
            return new Result().fail(0, "未找到用户");
        if (StringUtils.isNotBlank(user.getUserCar()))
            user.setIsRule(1);
        user.setId(tbUser.getId()).updateById();
        return success();
    }

    @GetMapping("/getInfo")
    @ApiOperation("查看用户信息")
    public Result getInfo() {
        return success(userService.getById(this.getUser().getId()));
    }


    @GetMapping("/getChildInfo")
    @ApiOperation("查看我的直推信息")
    public Result getChildInfo() {
        List<TbUser> list = userService.list(Wrappers.<TbUser>lambdaQuery().eq(TbUser::getParentId, this.getUser().getId()));

        list.forEach(item -> {
            item.setPhone(item.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
        });
        return success(list);
    }

    @GetMapping("/getMoneys")
    @ApiOperation("查看我的余额")
    public Result getMoneys() {
        TbMoneys moneys = moneysService.getOne(Wrappers.<TbMoneys>lambdaQuery().eq(TbMoneys::getUserId, this.getUser().getId()));
        return success(moneys);
    }

    //分享


}

